<?php

namespace yak\layui\behaviors;

use Yii;
use yak\layui\widgets\grid\LayuiListData;
use yii\data\ActiveDataProvider;
use yii\helpers\ArrayHelper;
use yii\web\HeaderCollection;
use yii\web\Request;
use yii\web\Response;

class LayuiSearchBehavior extends LayuiBehavior
{
    /**
     * @var array
     */
    protected $columns;

    /**
     * @var ActiveDataProvider
     */
    protected $dataProvider;

    /**
     * @var int
     */
    protected $count = 0;

    /**
     * @var int
     */
    protected $page = 1;

    /**
     * @var int
     */
    protected $pageSize = 10;

    public function run(HeaderCollection $headers, Request $request, array $params, Response $response)
    {
        // TODO: Implement run() method.
        $searchClass = $headers->get('Search-Class', null);
        if ($searchClass === null) {
            return $this->fail('class model not found!!');
        }

        $this->page = ArrayHelper::getValue($params, 'page', 1);
        $this->pageSize = ArrayHelper::getValue($params, 'per-page', 10);
        $orders = ArrayHelper::getValue($params, 'Sort', []);
        $conditions = ArrayHelper::getValue($params, 'Condition', []);
        $searchModel = Yii::createObject($searchClass);

        $this->dataProvider = $searchModel->search($conditions);
        $this->columns = $searchModel->columns();

        $defaultOrder = [];
        foreach ($orders as $key => $value) {
            if (empty($value)) continue;
            $defaultOrder[$key] = strcmp($value, 'desc') === 0 ? SORT_DESC : SORT_ASC;
        }
        $this->dataProvider->setSort(['defaultOrder' => $defaultOrder]);
        $this->dataProvider->setPagination(['page' => $this->page - 1, 'pageSize' => $this->pageSize]);

        $count = $headers->get('Cancel-Count', -1);
        $this->count = $count == -1 ? $this->dataProvider->getTotalCount() : $count;

        return $this->result();
    }


    protected function result()
    {
        try {

            $dataView = new LayuiListData([
                'dataProvider' => $this->dataProvider,
                'columns' => $this->columns
            ]);

            return $this->successData($dataView->renderData(), $this->count);
        } catch (\Exception $e) {
            return $this->fail($e->getMessage());
        }
    }

}